import { useState, useEffect } from "react";
import { Button, Row, Col, Form, message, Alert, Select, Modal } from "antd";
import CommonInput from "@/views/components/CommonInput";
import CommonSelect from '@/pages/OrderModule/common/components/CommonSelect';
import CommonTextarea from '@/pages/OrderModule/common/components/CommonTextarea';
import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { useAddress } from '@/pages/OrderModule/common/hooks/useAddress';
import CommonLoading from "@/components/CommonLoading";
import { find, isEmpty } from "lodash";
import { getAllArea, saveOrderAddress } from "../../../../../../services";
import Style from './index.module.less';

const Address = (props) => {
  const { actions, initValues, onChange, record, handleCancel, handleOk } = props;

  const [form] = Form.useForm();

  const [data, setData] = useState([]); //地址下拉数据
  const [citysData, setCitysData] = useState([]); //城市选择下拉
  const [districtsData, setDistrictsData] = useState([]); //区选择下拉
  const [streetData, setStreetData] = useState([]); //区选择下拉
  const [currentAreaItem, setCurrentAreaItem] = useState({}); //当前选择的省市区
  const [loading, setLoading] = useState(false);


  //获取省市区的数据
  const getAreaList = async () => {
    const res = await getAllArea({
      orderChannel: record.orderChannel,
      source: record.source
    });
    if (res.success) {
      setData(res.data);
    }
  };

  //京东和快手渠道获取街道的数据
  const getStreetData = async val => {
    const res = await getAllArea({
      orderChannel: record.orderChannel,
      level: 4,
      parentAreaId: val,
      source: record.source
    });
    if (res.success) {
      setStreetData(res.data);
    }
  };

  useEffect(() => {
    getAreaList();
    form.resetFields();
  }, []);

  useEffect(() => {
    const {
      provinceId,
      province,
      cityId,
      city,
      district,
      street,
      originProvinceId,
      originCityId,
      originDistrictId,
      originStreetId
    } = initValues;
    if (data.length) {
     try{
      if ([1, 9, 12].includes(record.orderChannel) && record.source != -1) {
        //需要展示街道
        const provincOobj = find(data, ["id", originProvinceId]);
        setCitysData(provincOobj?.childs);
        const cityOobj = find(provincOobj.childs, ["id", originCityId]);
        setDistrictsData(cityOobj?.childs);
        getStreetData(originDistrictId);
        form.setFieldsValue({
          provinceId: originProvinceId,
          cityId: originCityId,
          districtId: originDistrictId,
          streetId: originStreetId
        });
      } else {
        const provincOobj = find(data, ["id", provinceId]);
        setCitysData(provincOobj?.childs);
        const cityOobj = find(provincOobj.childs, ["id", cityId]);
        setDistrictsData(cityOobj?.childs);
      }
      setCurrentAreaItem({
        provinceName: province,
        cityName: city,
        areaName: district,
        street: street
      });
     }catch{}
    }
  }, [data, initValues]);

  const keyMap = {
    userKey: "name",
    phoneKey: "phone",
    provinceKey: "provinceId",
    cityKey: "cityId",
    areaKey: "districtId",
    addressKey: "address"
  };

  //地址识别
  const handleFormatData = e => {
    // const val = form.getFieldValue("addressRecognition");
    const val = e.target.value;
    if (val) {
      try {
        const result = AddressParse.parse(val.replace(/\s+/g, ""))[0];
        let provinceId, cityId, areaId;
        if (result.province && result.city && result.area) {
          const proObj =
            find(data, ["name", result.province.replace("省", "")]) ||
            find(data, ["name", result.province]) ||
            find(data, ["name", result.province + "省"]);
          provinceId = proObj.id;
          setCitysData(proObj?.childs);
          const cityObj = find(proObj.childs, ["name", result.city]);
          cityId = cityObj.id;
          setDistrictsData(cityObj?.childs);
          const areaObj = find(cityObj.childs, ["name", result.area]);
          areaId = areaObj.id;
          const obj2 = {};
          obj2.provinceName = result.province;
          obj2.cityName = result.city;
          obj2.areaName = result.area;
          setCurrentAreaItem(obj2);
        }
        form.setFieldsValue({
          name: result.name,
          phone: result.mobile,
          address: result.details.length > 120 ? result.details.slice(0, 120) : result.details,
          provinceId: provinceId,
          cityId: cityId,
          districtId: areaId
        });
      } catch (error) {
        message.error("地址识别失败");
      }
    } else {
      message.warning("请输入识别内容！");
    }
  };

  //提交地址
  async function saveAddress(values) {
    const { provinceName, cityName, areaName, street } = currentAreaItem;
    // const values = form.getFieldsValue();
    const { name, phone, address, provinceId, cityId, districtId, streetId } = values;
    if (record.orderChannel == 15) {
      //抖音平台
      if (phone == initValues.phone) {
        return Modal.info({
          title: "修改地址提示",
          okText: "知道了",
          content: (
            <div>
              抖音订单，部分收货地址修改时，<span className="common-color9">手机号</span>必须明文输入
            </div>
          ),
          onOk() { }
        });
      }
    } else if (record.orderChannel == 8) {
      //淘宝平台
      if (address == initValues.address) {
        return Modal.info({
          title: "修改地址提示",
          okText: "知道了",
          content: (
            <div>
              淘宝订单，部分收货地址修改时，<span className="common-color9">详细地址</span>必须明文输入
            </div>
          ),
          onOk() { }
        });
      }
    }
    setLoading(true);
    const { success, msg } = await saveOrderAddress({
      address: address != initValues?.address ? address : undefined,
      city: cityName,
      cityId: cityId,
      district: areaName,
      districtId: districtId,
      street: street ? street : undefined,
      streetId: streetId,
      id: record.id,
      name: name != initValues?.name ? name : undefined,
      phone: phone != initValues?.phone ? phone : undefined,
      province: provinceName,
      provinceId: provinceId,
      operationPage: actions == "sysOrder" ? "2" : "3"
    });
    setLoading(false);
    if (success) {
      message.success(msg);
      // handleOk();
    } else {
      message.error(msg);
    }
  }

  //输入框获取焦点
  const handleFocus = (e, code) => {
    const val = e.target.value;
    if (val.includes("*")) {
      form.setFieldsValue({
        [code]: ""
      });
    }
  };

  //输入框失去焦点
  const handleBlur = (e, code) => {
    const val = e.target.value;
    if (val == "") {
      form.setFieldsValue({
        [code]: initValues[code]
      });
    } else if (val.includes("*")) {
      form.setFieldsValue({
        [code]: ""
      });
    }
  };

  //省的选择
  const handleProvinceChange = e => {
    form.setFieldsValue({
      cityId: "",
      districtId: "",
      streetId: ""
    });
    const provincOobj = find(data, ["id", e]);
    setCitysData(provincOobj?.childs);
    setDistrictsData([]);
    setStreetData([]);
    setCurrentAreaItem({
      provinceName: provincOobj.name
    });
  };

  //市的选择
  const handleCityChange = e => {
    form.setFieldsValue({
      districtId: "",
      streetId: ""
    });
    const cityOobj = find(citysData, ["id", e]);
    setDistrictsData(cityOobj?.childs);
    setStreetData([]);
    setCurrentAreaItem({
      ...currentAreaItem,
      cityName: cityOobj.name
    });
  };

  //区的选择
  const handleDistrictChange = (e, Option) => {
    form.setFieldsValue({
      streetId: ""
    });
    setCurrentAreaItem({
      ...currentAreaItem,
      areaName: Option.children
    });
    {
      [1, 12].includes(record.orderChannel) && record.source != -1 && getStreetData(e);
    }
  };

  //点击提交
  const onSubmit = () => {
    form.validateFields().then(val => {
      saveAddress(val);
    });
  };

  //省下拉
  const proviceOptions =
    !isEmpty(data) &&
    data.map(d => (
      <Option value={d.id} key={d.id}>
        {d.name}
      </Option>
    ));

  //市下拉
  const cityOptions =
    !isEmpty(citysData) &&
    citysData.map(d => (
      <Option value={d.id} key={d.id}>
        {d.name}
      </Option>
    ));

  //区下拉
  const districtsOptions =
    !isEmpty(districtsData) &&
    districtsData.map(d => (
      <Option value={d.id} key={d.id}>
        {d.name}
      </Option>
    ));

  //街道下拉
  const streetOptions =
    !isEmpty(streetData) &&
    streetData.map(d => (
      <Option value={d.id + ""} key={d.id}>
        {d.name}
      </Option>
    ));

  return (
    <CommonForm
      className={Style.address_group}
      formProps={{
        form,
        initialValues: initValues,
        onValuesChange(changedValues, values) {
          onChange?.((pre) => ({ ...pre, ...values }));
        },
      }}
      columns={[
        {
          block: (
            <>
              <Row gutter={[16, 16]}>
                <Col span={8}>
                  <Form.Item rules={[{ required: true, message: "请输入收件人" }]} name="name">
                    <CommonInput
                      onFocus={e => handleFocus(e, "name")}
                      onBlur={e => handleBlur(e, "name")}
                      aria-required
                      showCount={true}
                      maxLength={30}
                      placeholder="请输入收件人"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item rules={[{ required: true, message: "请输入手机号或固话或虚拟号" }]} name={keyMap.phoneKey}>
                    <CommonInput
                      onFocus={e => handleFocus(e, "phone")}
                      onBlur={e => handleBlur(e, "phone")}
                      aria-required
                      placeholder="请输入手机号或固话或虚拟号"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item rules={[{ required: true, message: "请选择省" }]} name={keyMap.provinceKey}>
                    <CommonSelect
                      onChange={handleProvinceChange}
                      aria-required
                      showSearch
                      filterOption={(input, option) => (option?.children ?? "").toLowerCase().includes(input.toLowerCase())}
                    >
                      {proviceOptions}
                    </CommonSelect>
                  </Form.Item>
                </Col>
              </Row>
              <Row gutter={[16, 16]}>
                <Col span={8}>
                  <Form.Item rules={[{ required: true, message: "请选择市" }]} name={keyMap.cityKey}>
                    <CommonSelect
                      onChange={handleCityChange}
                      aria-required
                      showSearch
                      filterOption={(input, option) => (option?.children ?? "").toLowerCase().includes(input.toLowerCase())}
                    >
                      {cityOptions}
                    </CommonSelect>
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item rules={[{ required: true, message: "请选择区" }]} name={keyMap.areaKey}>
                    <CommonSelect
                      onChange={(e, Option) => {
                        handleDistrictChange(e, Option);
                      }}
                      aria-required
                      showSearch
                      filterOption={(input, option) => (option?.children ?? "").toLowerCase().includes(input.toLowerCase())}
                    >
                      {districtsOptions}
                    </CommonSelect>
                  </Form.Item>
                </Col>
                {[1, 12].includes(record.orderChannel) && record.source != -1 ? (
                <Col span={8}>
                  <Form.Item rules={[{ required: true, message: "请选择街道" }]} name={"streetId"}>
                    <CommonSelect
                      onChange={(e, Option) => {
                        setCurrentAreaItem({
                          ...currentAreaItem,
                          street: Option.children
                        });
                      }}
                      aria-required
                      showSearch
                      filterOption={(input, option) => (option?.children ?? "").toLowerCase().includes(input.toLowerCase())}
                    >
                      {streetOptions}
                    </CommonSelect>
                  </Form.Item>
                </Col>
              ) : (
                ""
              )}
              </Row>
              <Row gutter={[16, 16]}>
                <Col span={8}>
                  <Form.Item name={keyMap.addressKey} rules={[{ required: true, message: "请输入详细地址" }]}>
                    <CommonTextarea
                      style={{ height: "100px" }}
                      aria-required
                      onFocus={e => handleFocus(e, "address")}
                      onBlur={e => handleBlur(e, "address")}
                      showCount={true}
                      maxLength={500}
                      placeholder="请输入详细地址"
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item name="addressRecognition">
                    <CommonTextarea
                      placeholder="地址识别粘贴地址回车后自动识别，例如：张三，15712345678，广东省 广州市 天河区 平安大厦"
                      onPressEnter={handleFormatData}
                      style={{ height: "100px" }}
                      showCount={true}
                      maxLength={100}
                    />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Button type="primary" onClick={onSubmit}>保存</Button>
                </Col>
              </Row>
            </>
          ),
        },
      ]}
    ><CommonLoading loading={loading} /></CommonForm>
  );
};

export default Address;
